<?php
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2016/5/24
 * Time: 17:04
 */
define('TX', 3);
class PartnerAction extends Action{
    public function getQuanUserList($fullName=null,$order="quser.createTime", $orderBy="desc", $start = 0, $limit = 25,$express=0) {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $MiModel = M("quan_user");
        $mimall = M("mimall");
        Session::switchCustomer($cid);
        if($fullName){
            $condition["auser.fullName"] = array("like", "%".$fullName."%");
        }
        $quanInfo = $mimall->alias("a")
            ->join("inner join wx_miyouquan b on a.id = b.mallId")
            ->where("a.fromCustomerId=$cid and deleted = 0")
            ->field("b.id")
            ->find();
        $qid = $quanInfo['id'];
        //$condition["quser.deleted"] = array("eq",0);
        $condition["quser.qid"] = array("eq",$qid);
        if(!$express){
            $arr = $MiModel->alias("quser")
                ->field("quser.*,c.nickName as rNickName,c.headImgUrl as rHeadImgUrl,auser.phone,auser.fullName,d.teamLeader")
                ->join("wx_quan_user c on quser.refereeUid = c.uid and c.qid=$qid")
                ->join("wx_all_user as auser on auser.id=quser.uid")
                ->join("wx_quan_team d on quser.teamId=d.id and d.deleted=0")
                ->where($condition)->order("$order $orderBy")
                ->group("quser.id")
                ->limit("$start, $limit")->select();
            if ($arr) {
                $count = $MiModel->alias("quser")->field("*,quser.createTime as createTime,auser.id as id")->join("wx_all_user as auser on auser.id=quser.uid")->where($condition)->count();
                Output::instance()->objArray($arr, $count);
            } else {
                Output::instance()->resultCode(code_success);
            }
        }else{
            $arr = $MiModel->alias("quser")
                ->field("quser.nickName,quser.status,quser.deleted,auser.fullName,auser.phone,quser.identity,quser.miCoins,c.nickName as rNickName,quser.createTime")
                ->join("wx_quan_user c on quser.refereeUid = c.uid and c.qid=$qid")
                ->join("wx_all_user as auser on auser.id=quser.uid")
                ->where($condition)->order("$order $orderBy")
                ->group("quser.id")->select();
            $data[0] = array(
                'nickName'=>'用户名',
                'status'=>'审核状态',
                'deleted' => '删除情况',
                'fullName'=>'姓名',
                'phone' => '手机',
                'identity' =>'身份',
                'miCoins'=>'收入',
                'rNickName'=>'推荐人',
                'createTime'=>'创建时间',
                'isNum'=>'6',
                'istitle'=>'1'
            );
            foreach ($arr as $k1 => $v1) {
                if($v1['status']==1){
                    $v1['status'] = '审核通过';
                }else{
                    $v1['status'] = '等待审核';
                }
                if($v1['deleted']==1){
                    $v1['deleted']='已淘汰';
                }else{
                    $v1['deleted']='已激活';
                }
                if($v1['identity']==1){
                    $v1['identity']='密友';
                }else{
                    $v1['identity']='主公';
                }
                $data[] = $v1;
            }
            Output::instance()->objArrayExcel('密友列表'.date("Y-m-d H:i:s"), '', $data);
        }
    }
    public function getwithdrawpayList($qid = NULL,$name=NUll,$nickName=NULL,$startTime=NULL,$endTime=NULL,$state=NULL,$start=0,$limit=10,$isExport = NULL,$type = NULL){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $MiconisTxModel = M("miconis_tixian");
        $mimall = M("mimall");
        Session::switchCustomer($cid);
        if(empty($qid)){
            $quanInfo = $mimall->alias("a")
                ->join("inner join wx_miyouquan b on a.id = b.mallId")
                ->where("a.fromCustomerId=$cid and deleted = 0")
                ->field("b.id")
                ->find();
            $qid = $quanInfo['id'];
        }

        $where["tx.quanId"]=array("eq",$qid);
        $where["qu.deleted"]=array("eq",0);
        if (!empty($name) && $name !=='') {
            $where['myq.name'] = array('like', "%$name%");
        }
        if (!empty($nickName) && $nickName !=='') {
            $where['qu.nickName'] = array('like', "%$nickName%");
        }
        if ($state!==NUll && $state!=='') {
            $where['tx.state'] = $state;
        }
        if ($type!==NUll && $type!=='') {
            $where['tx.type'] = $type;
        }
        if ($startTime != '' && $endTime != '') {
            $where['tx.createTime'] = array(array('egt',$startTime),array('elt',$endTime));
        } else if ($startTime != '') {
            $where["tx.createTime"] = array('egt', $startTime);
        } else if ($endTime != '') {
            $where["tx.createTime"] = array('elt', $endTime);
        }
        if ($isExport) {
            $arr = $MiconisTxModel->alias('tx')
                ->join("LEFT JOIN  wx_quan_user as qu ON qu.uid = tx.uId and qu.qid = tx.quanId")
                ->join("LEFT JOIN  wx_".$cid."_user_weixin_info as wx ON wx.userId = tx.uId")
                ->join("LEFT JOIN  wx_miyouquan as myq ON tx.quanId = myq.id")
                ->where($where)
                ->field("myq.name,qu.nickName,qu.headImgUrl,wx.nickname as wxNickName,wx.headimgurl as wxHeadImgUrl,qu.miCoins,tx.cash,tx.state,tx.createTime,tx.id,tx.type,tx.bankCardName")
                ->order('tx.createTime desc')
                ->select();
            foreach ($arr as $key => $value) {
                if ($value['state'] == 1) {
                    $arr[$key]['state'] = '已提现';
                }else{
                    $arr[$key]['state'] = '提现中';
                }
                if($value['type'] == 1){
                    $arr[$key]['type'] = '提现到钱包';
                }elseif($value['type'] == 2){
                    $arr[$key]['type'] = '提现到零钱';
                }elseif($value['type'] == 3) {
                    $arr[$key]['type'] = '提现到银行卡';
                    $bankAccount = json_decode($value['bankAccount'], true);
                    $arr[$key]['bankAccount'] = $bankAccount['bankCardName'] . ':' . $bankAccount['bankAccountName'] . '-' . $bankAccount['bankCardNum'];
                }

            }
            $expCellName  = array(
                //array('name','商品名称'),
                array('nickName','用户'),
                array('cash','提现金额'),
                array('miCoins','余额'),
                array('state','状态'),
                array('type', '提现方式'),
                array('bankAccount', '银行账户信息'),
                array('createTime','申请时间'),
            );
            Output::instance()->objArrayExcel('密友提现表', $expCellName, $arr);
        }else{
            $arr = $MiconisTxModel->alias('tx')
                ->join("LEFT JOIN  wx_quan_user as qu ON qu.uid = tx.uId and qu.qid = tx.quanId")
                ->join("LEFT JOIN  wx_".$cid."_user_weixin_info as wx ON wx.userId = tx.uId")
                ->join("LEFT JOIN  wx_miyouquan as myq ON tx.quanId = myq.id")
                ->where($where)
                ->limit($start,$limit)
                ->field("myq.name,qu.nickName,qu.headImgUrl,wx.nickname as wxNickName,wx.headimgurl as wxHeadImgUrl,FORMAT(qu.miCoins,2) as miCoins,FORMAT(tx.cash,2) as cash,tx.state,tx.createTime,tx.id,tx.type,tx.bankAccount")
                ->order('tx.createTime desc')
                ->select();
        }
        if ($arr) {
            $count = $MiconisTxModel->alias('tx')
                ->join("LEFT JOIN  wx_quan_user as qu ON qu.uid = tx.uId and qu.qid = tx.quanId")
                ->join("LEFT JOIN  wx_miyouquan as myq ON tx.quanId = myq.id")
                ->where($where)
                ->field("myq.name,qu.nickName,qu.headImgUrl,FORMAT(qu.miCoins,2) as miCoins,FORMAT(tx.cash,2) as cash,tx.state,tx.createTime,tx.id,tx.type,tx.bankAccount")
                ->order('tx.createTime desc')
                ->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode(code_success);
        }
    }

    public function savewithdrawpaymsg($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $MiconisTxModel = M("miconis_tixian");
        $CustomerMallSettingModel = D('customer_mall_setting');
        Session::switchCustomer($cid);
        $data['completeTime'] = date("Y-m-d H:i:s");
        $data['state'] = 1;
        $where['tx.id'] = $id;
        $where["b.cId"]=array("eq",$cid);
        $oldarr = $MiconisTxModel->alias('tx')
            ->join("inner join wx_mimall_user b on tx.quanId=b.qId and tx.uId=b.uId")
            ->field("tx.*,b.openid")
            ->where($where)->find();
			Log::write("体现 ".$MiconisTxModel->getLastSql());
        $condition['customerId'] = $cid;
        $mallInfo = $CustomerMallSettingModel->where($condition)->find();
        /* 	if ($oldarr['miCoins']< $oldarr['cash']) {
                Output::instance()->resultCode(code_product_refund_failed_miCoins);
                return;
            } */

        $MiconisTxModel->startTrans();
        $rollback1 = WeixinApi::transferAccountsByOpenId($oldarr['openid'], $oldarr['cash'],'销售奖励，加油！',false,$mallInfo['payKey'],$mallInfo['mchId'],$mallInfo['appId']);
        // 原来提现方式采用红包接口
        // $rollback1 = WeixinApi::sendRedEnvelopeByOpenId('密友圈',$oldarr['openid'], $oldarr['cash'],'销售佣金，加油！');
        Log::write("红包信息：". $oldarr['openid'] ."---". $oldarr['cash']);
        if ($oldarr && $rollback1) {
            $txwhere['tx.id']= $id;
            $rollback2 = $MiconisTxModel->alias('tx')->where($txwhere)->save($data);
            Log::write("存入提现状态:".$MiconisTxModel->getLastSql());
        }
        $qwhere['uid'] = $oldarr['uId'];
        $qwhere['qid'] = $oldarr['quanId'];
        $cash = $oldarr['cash'];
        Log::write("提现sql错误：". $rollback1 ."---". $rollback2);
        if ($rollback1&&$rollback2!==false) {
            $MiconisTxModel->commit();
            Output::instance()->resultCode(code_success);
        }else{
            $MiconisTxModel->rollback();
            Output::instance()->object([
                'code'=>1,
                'msg'=>'提现失败',
            ]);
        }
    }
    public function getQuanId(){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $mimall = M("mimall");
        Session::switchCustomer($cid);
        $quanInfo = $mimall->alias("a")
            ->join("inner join wx_miyouquan b on a.id = b.mallId")
            ->where("a.fromCustomerId=$cid and deleted = 0")
            ->field("b.id")
            ->find();
        Output::instance()->object($quanInfo);
    }

    /**
     * 修改平台提现设置信息
     * @param $withdrawConfig	提现设置
     */
    public function updateQuanWithdraw($withdrawConfig){
        /** 1.判断用户身份 */
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];

        /** 2.实例化表 */
        Session::switchCustomer(0);
        $cuSettingMedol = M('customer_setting');
        Session::switchCustomer($cid);

        $info = $cuSettingMedol->where(['cid' => $cid])->find();
        if(empty($info)){
            /** 3。添加 */
            $data['withdrawConfig'] = $withdrawConfig;
            $data['cid'] = $cid;
            $result = $cuSettingMedol->add($data);
        }else{
            /** 3。修改 */
            $result = $cuSettingMedol->where(['cid' => $cid])->setField('withdrawConfig', $withdrawConfig);
        }



        /** 4。返回 */
        if(is_numeric($result)){
            $sql = $cuSettingMedol->getLastSql();
            R('Log/add',array('marketing','','营销圈',op_add,$sql,'修改营销圈提现设置'));
            Output::instance()->object([
                'code'=>0,
                'msg'=>'保存成功',
            ]);
        }else{
            Output::instance()->object([
                'code'=>1,
                'msg'=>'保存失败',
            ]);
        }
    }

    /**
     * 密友提现
     * @param $id	提现Id
     */
    public function miuWithdraw($id){
        /** 1.判断用户身份 */
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];

        /** 2.实例化表 */
        Session::switchCustomer(0);
        $tixianModel = M('miconis_tixian');
        $purseModel = M('module_user_purse');
        $purseBillModel = M('module_user_purse_bill');
        Session::switchCustomer($cid);
        $tixianModel->startTrans();

        /** 3.查询提现详情 */
        $tixianInfo = $tixianModel->alias('tx')->join('wx_miyouquan as quan on tx.quanId = quan.id')->where(['tx.id' => $id])->field('tx.*,quan.cId')->find();

        if($tixianInfo['status'] == 1){
            Output::instance()->object([
                'code'=>1,
                'msg'=>'提现失败',
            ]);
            return;
        }

        $data['state'] = 1;
        $data['completeTime'] =  date("Y-m-d H:i:s");
        $result = $tixianModel->where(['id' => $id])->save($data);

        /** 4.判断提现方式 */
        if($tixianInfo['type'] == 1){		//提现到钱包
            $where['userId'] = array('eq', $tixianInfo['uId']);
            $where['cid'] = array('eq', $tixianInfo['cId']);

            $purseInfo = $purseModel->where($where)->find();
            if(empty($purseInfo)){
                $purseData['cid'] = $tixianInfo['cId'];
                $purseData['userId'] = $tixianInfo['uId'];
                $purseData['totalRecharge']=0;
                $purseData['balance']=0;
                $purseData['updateTime']=date("Y-m-d H:i:s");
                $purseModel->add($purseData);
            }
            $purseRes = $purseModel->where($where)->setInc('balance', $tixianInfo['cash']);
            $purseBillData['cid'] = $tixianInfo['cId'];
            $purseBillData['userId'] = $tixianInfo['uId'];
            $purseBillData['module'] = 'withdraw';
            $purseBillData['description'] = '提现';
            $purseBillData['moduleId'] = $tixianInfo['id'];
            $purseBillData['money'] = $tixianInfo['cash'];
            $purseBillData['type'] = TX;
            $purseBillData['createTime'] = date("Y-m-d H:i:s");
            $purseBillData['deleted'] = 0;
            $purseBillRes = $purseBillModel->where($where)->add($purseBillData);
            if(is_numeric($purseRes) && $purseBillRes && $result){
                $tixianModel->commit();
                Output::instance()->object([
                    'code'=>0,
                    'msg'=>'提现成功',
                ]);
            }else{
                $tixianModel->rollback();
                Output::instance()->object([
                    'code'=>1,
                    'msg'=>'提现失败',
                ]);
            }
        }elseif($tixianInfo['type'] == 2){ //提现到零钱
            $tixianModel->rollback();
             self::savewithdrawpaymsg($id);
        }elseif($tixianInfo['type'] == 3){//提现到银行卡
            $setting = R("CUser/getMallSetting");
            $bankAccount = json_decode($tixianInfo['bankAccount'], true);
//			$partnerkey = '', $mch_id, $amount, $enc_bank_no, $enc_true_name, $bank_code, $desc = ''
//			{'bankAccountName':'1','bankAccountNum':'1','bankCardNum':'1','bankCardName':'1'}
            $bankRes = WxpayAction::pay_bank($setting['payKey'], $setting['mchId'], $tixianInfo['cash'], $bankAccount['bankCardNum'], $bankAccount['bankAccountName'], $bankAccount['bankWxNum'],'提现');
            if($bankRes->result_code == 'SUCCESS' && $result){
                $tixianModel->commit();
                Output::instance()->object([
                    'code'=>0,
                    'msg'=>'提现成功',
                ]);
            }else{
                $tixianModel->rollback();
                Output::instance()->object([
                    'code'=>1,
                    'msg'=>'提现失败',
                ]);
            }

        }




    }

    /**
     * 平台提现配置详情
     */
    public function withdarwConfig(){
        /** 1.判断用户身份 */
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];

        /** 2.实例化数据库 */
        Session::switchCustomer(0);
        $cuSettingModel=M("customer_setting");
        Session::switchCustomer($customerId);

        /** 3.查询提现设置详情 */
        $withdrawConfig = $cuSettingModel->where(['cid' => $customerId])->getField('withdrawConfig');
        if($withdrawConfig){
            $out['code']= 0;
            $out['msg']= 'ok';
            $out['withdrawConfig']= $withdrawConfig;
        }else{
            $out['code']= 1;
            $out['msg']= 'fial';
            $out['withdrawConfig']= [];
        }
        Output::instance()->object($out);
    }

}